#include "fmtableview.h"

#include <QAbstractItemView>
#include <QModelIndex>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QHeaderView>
#include <QFile>
#include <QFileInfo>
#include <QSet>
#include <QDebug>

namespace kepen {
namespace core {


FmTableView::FmTableView(QWidget *parent)
    :QTableView{parent}
{
    setSelectionBehavior(QAbstractItemView::SelectionBehavior::SelectRows);
    setEditTriggers(QAbstractItemView::EditTrigger::NoEditTriggers);

    //隔行颜色
    setAlternatingRowColors(true);
    //隐藏左侧(自动生成的)序号，原因：分页，第n(n>1)页的其实序号不是从1开始 ，是从PageSize*n开始
    QHeaderView *v= verticalHeader() ;
    v->hide();
    // horizontalHeader()->setObjectName("hHeader");
    // verticalHeader()->setObjectName("vHeader");
    //最后一列填充满表格
    // horizontalHeader()->setStretchLastSection(true);
    //设置tableview所有列的默认行高
    // ui->tableView->verticalHeader()->setDefaultSectionSize(30);
    //自动排序功能
    //tableView->setSortingEnabled(true);
    QFile file(":/resources/uiqss/mytableview.txt");
    bool ok = file.open(QIODevice::ReadOnly | QIODevice::Text);
    if(ok)
    {
        //带BOM的存储文件,原始byte[] 是3个字节(ef,bb,bf),只有转换成
        // Qt 使用这种方式，能自动跳过 0xfeff
        QTextStream stream(&file);
        stream.setEncoding(QStringConverter::Utf8);
        QString txt =  stream.readAll();
        this->setStyleSheet(txt);
        // qDebug().noquote()  <<__FILE__ <<",Line:"<<__LINE__ <<txt;
    }


    setFocusPolicy(Qt::StrongFocus);

    //去除选中虚线框
    // this->setFocusPolicy(Qt::FocusPolicy::NoFocus);
}

FmTableView::~FmTableView()
{

}

void FmTableView::keyPressEvent(QKeyEvent *event)
{
    int k= event->key();

    if(Qt::Key_Delete == k ||Qt::Key_Backspace == k)
    {
        Q_EMIT keyPress4Page(k);
        return;
    }else if(Qt::Key_Up == k ||Qt::Key_Down == k)
    {
        keyPressUpDown(k);
        return;
    }else if(Qt::Key_PageUp == k ||Qt::Key_PageDown == k)
    {

        Q_EMIT keyPress4Page(k);
        return;
    }
    QTableView::keyPressEvent(event);
}

void FmTableView::refreshBy(kemod::KeFootmark *node)
{
    QAbstractItemModel *model = this->model();
    int rowTotal = model->rowCount();
    QStandardItemModel *theModel =  dynamic_cast<QStandardItemModel*>(model);
    if(1 == rowTotal){
        node2UI(theModel,node,0);
    }else if(rowTotal > 1)
    {
        QModelIndexList list =  selectedIndexes();
        if(list.count() >0)
        {
            QModelIndex index = selectionModel()->currentIndex();
            int row = index.row();
            node2UI(theModel,node,row);

        }
    }


}





void FmTableView::setData(int startIndex,int count,kepen::kemod::KeFootmark*vs)
{
    int i=0,tt=startIndex;
    kepen::kemod::KeFootmark * node = vs;
    QStandardItem * aItem;
    QAbstractItemModel *lastModel = model();
    QStandardItemModel *theModel ;
    QWidget *parent=this->parentWidget();
    theModel = new QStandardItemModel(parent);
    QStringList headerLabels = {"ID","序号","版本号","名称", "地址", "时间","level"};



    theModel->setHorizontalHeaderLabels(headerLabels);

    // qDebug()  << __FILE__ << " ,Line:  "<< __LINE__ << " startIndex: "<<startIndex  ;
    // theModel->verticalHeader()->setHidden(true);

    for(;i<count;++i,++node)
    {
        ++tt;


        aItem = new QStandardItem(node->id);
        theModel->setItem(i,0,aItem);
        //序号
        aItem=new QStandardItem();
        aItem->setData(tt,Qt::ItemDataRole::DisplayRole);

        theModel->setItem(i,1,aItem);

        node2UI(theModel,node,i);

    }

    if(lastModel)
    {
        lastModel->deleteLater();
    }
    this->setModel(theModel);


    // id
    this->hideColumn(0);
    //序号
    this->setColumnWidth(1,36);
    // version
    // this->hideColumn(2);
    //需要改变行高即可。在设置完数据后调用
    resizeRowsToContents();



}



QString FmTableView::getSelectedNodeID()
{
    QAbstractItemModel *model = this->model();
    int rowTotal = model->rowCount();

    if(1 == rowTotal)
    {
        QModelIndex cell = model->index(0, 0);
        QString dataID = model->data(cell).toString();
        return dataID;
    }else if(rowTotal>1)
    {
        QModelIndexList list =  selectedIndexes();
        if(list.count() >0)
        {
            QModelIndex index = selectionModel()->currentIndex();
            int row = index.row();

            QModelIndex cell = model->index(row, 0);
            QString dataID = model->data(cell).toString();
            return dataID;

        }

    }
    return "";
}

void FmTableView::getSelectedNodeIDs(std::vector<kepen::kemod::IdVersionTag> &vs)
{
    QAbstractItemModel *model = this->model();
    int rowTotal = model->rowCount();

    if(1 == rowTotal)
    {
        int s;
        kepen::kemod::IdVersionTag tag;
        QModelIndex idCell = model->index(0, 0);
        QModelIndex verCell = model->index(0, 2);
        QString dataID = model->data(idCell).toString();
        int v = model->data(verCell).toInt();
        const ushort *ptr = dataID.utf16();
        memset(&tag,0,sizeof(tag));
        tag.version = v;
        s = dataID.length();
        s<<=1;
        memcpy(&tag.id,ptr,s);

        vs.push_back(tag);

    }else if(rowTotal>1)
    {
        QModelIndexList listSelected =  selectedIndexes();
        if(listSelected.count() >0)
        {
            int s;
            const ushort *ptr;
            kepen::kemod::IdVersionTag tag;
            QSet<int> vn;

            for(const QModelIndex &index :listSelected){

                int row = index.row();
                if(false == vn.contains(row))
                {
                    QModelIndex idCell = model->index(row, 0);
                    QModelIndex verCell = model->index(row, 2);
                    QString dataID = model->data(idCell).toString();
                    int v = model->data(verCell).toInt();
                    ptr = dataID.utf16();
                    memset(&tag,0,sizeof(tag));
                    tag.version = v;
                    s = dataID.length();
                    s<<=1;
                    memcpy(&tag.id,ptr,s);
                    vs.push_back(tag);

                    vn.insert(row);
                }

            }

        }

    }
}

void FmTableView::node2UI(QStandardItemModel *theModel, kemod::KeFootmark *node, int rowIdx)
{
    int j=2;
    QStandardItem * aItem;


    aItem=new QStandardItem();
    aItem->setData(node->version,Qt::ItemDataRole::DisplayRole);
    theModel->setItem(rowIdx,j,aItem);

    aItem = new QStandardItem(node->name);
    // aItem->setData(tt,Qt::ItemDataRole::DisplayRole);
    theModel->setItem(rowIdx,++j,aItem);

    aItem = new QStandardItem(node->address);
    theModel->setItem(rowIdx,++j,aItem);

    aItem = new QStandardItem(node->createTime);
    theModel->setItem(rowIdx,++j,aItem);


    aItem=new QStandardItem();
    aItem->setData(node->level,Qt::ItemDataRole::DisplayRole);
    theModel->setItem(rowIdx,++j,aItem);

}

void FmTableView::keyPressUpDown(int key)
{
    QAbstractItemModel *model = this->model();
    int rowTotal = model->rowCount();
    if(1==rowTotal)
    {
        QModelIndexList listSelected =  selectedIndexes();
        if(listSelected.count() >0){

        }
        else
        {
            setCurrentIndex(model->index(0, 0));
        }
    }else if(rowTotal>1)
    {
        QModelIndexList listSelected =  selectedIndexes();
        if(listSelected.count() >0){
            QModelIndex index = selectionModel()->currentIndex();
            int row = index.row();
            if(Qt::Key_Up == key){
                --row;
            }else if(Qt::Key_Down ==key){
                ++row;
            }
            if(rowTotal == row)row = 0;
            else  if(-1==row)row = rowTotal-1;
            setCurrentIndex(model->index(row, 1));
        }
        else
        {
            setCurrentIndex(model->index(0, 1));
        }
    }
}





}
}
